<?php
class FileWatch{
	
	//根目录
	public $baseURI='';
	//根链接
	public $baseURL='';	
	//需要管理的文件的绝对路径
	protected $path='';
	//过滤参数
	public $filter=array();
	//文件总数
	public $fileNum=0;

	function fileWatch($path=''){
		if(!empty($path))
			$this->path=$path;
		
		if(empty($this->path))
			throw_exception("Assign path");
			
		if(!is_dir($this->path))
			throw_exception("Path is not exists");
	}
	//获取文件
	function getFiles(){
		$filter=$this->filter;
		if(empty($filter['type'])){
			return $this->readFile();
		}
	}
	//读取指定路径下文件
	public function readFile($path=''){
		$files=array();
		$num=$numItem=0;
		$filter=$this->filter;
		$uploadPath=$this->path;
		$path=$uploadPath.$path;
		if(substr($path, -1)!='/')
			$path.='/';
			
		if(!empty($filter['limit'])){
			$limit=$filter['limit'];
		}else{
			$limit='0,10';
		}
			
		if(strpos($limit, ',')===false){
			$limitArr=array(0,10);
		}else{
			$limitArr=explode(',',$limit);
		}
			
		$handle=opendir($path);
		while(false !== ($file = readdir($handle))) {

			if($limitArr[1]>$numItem){				
				if(is_file($path.$file) && $num >= $limitArr[0]){
					$files[]=$this->getFileInfo($path.$file);
					$numItem++;
				}
			}
			
			if(!is_dir($path.$file))
				$num++;
		}
		closedir($handle);	
		$this->fileNum=$num;
		if(!empty($files))$files=stickysort($files,'date',DESC_AZ);
		return $files;
	}
	//获取文件属性及相关信息
	public function getFileInfo($file){
		if(!file_exists($file))
			throw_exception("File not exists");

		if(!is_file($file))
			throw_exception("Unknow file");
			
		$type=strtolower(str_replace('.','',strrchr($file, '.')));

		if(!empty($this->baseURI))
			$filePath=str_replace($this->baseURI, '', $file);
			
		if(in_array($type, array('jpg','gif','png'))){
			$imgInfo=getimagesize($file);			
			return array('name'=>$filePath,'type'=>$type,'size'=>$imgInfo[0].'*'.$imgInfo[1],'date'=>date("Y-m-d H:i:s", filectime($file)));
		}else{
			return array('name'=>$filePath,'type'=>$type,'size'=>'*','date'=>date("Y-m-d H:i:s", filectime($file)));
		}
	}
	//读取目录
	public function readDir($path=''){
		$dirs=array();
		$uploadPath=$this->path;
		$path=$uploadPath.$path;
		if(substr($path, -1)!='/')
			$path.='/';
			
		$handle=opendir($path);
		while(false!==($dir=readdir($handle))){
			if(is_dir($path.$dir) && !is_link($path.$dir) && strpos($dir, '.')===false)
			$dirs[]=$dir;
		}
		return $dirs;
	}
}